package cn.dexter.poker.redmine.dingding.service;

import cn.dexter.poker.redmine.dingding.commons.MemoryData;
import cn.dexter.poker.redmine.dingding.config.RedmineConfig;
import cn.dexter.poker.redmine.dingding.dao.PhoneDao;
import cn.dexter.poker.redmine.dingding.dao.ProjectDao;
import cn.dexter.poker.redmine.dingding.model.DingMessage;
import cn.dexter.poker.redmine.dingding.model.Project;
import cn.dexter.poker.redmine.dingding.model.RedmineTask;
import cn.dexter.poker.redmine.dingding.util.HttpUtil;
import cn.dexter.poker.redmine.dingding.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author DexterPoker
 * @version 创建时间：2018/12/20 9:53
 */

@Service
@Slf4j
public class RedmineService {

    @Resource
    private DingDingService dingDingService;

    @Resource
    private MemoryData memoryData;

    @Resource
    private RedmineConfig redmineConfig;

    @Autowired
    ProjectDao projectDao;

    @Autowired
    PhoneDao phoneDao;

    @Value("${redmine.template}")
    private String template;

    public String redmineRequestHandler(JSONObject json) {
        try {
            JSONObject root = json.getJSONObject("payload");
            JSONObject issue = root.getJSONObject("issue");
            JSONObject projectJson = issue.getJSONObject("project");
            String projectName = projectJson.getString("name");//项目名称
            System.out.println(projectName);
            if (StringUtil.isEmpty(projectName)) {
                return "获取项目名称失败";
            }
            List<Project> projects = projectDao.list();
            Project project = null;
            String username = null;
            for (Project p : projects) {
                if (p.getName().equals(projectName)) {
                    log.info("projectName", p.getName());
                    project = p;
                    //设置指派人信息
                    JSONObject assigneeJson = issue.getJSONObject("assignee");
                    username = assigneeJson.getString("lastname") + assigneeJson.getString("firstname");
                    String mobilePhone = phoneDao.mobilePhone(username);
                    HashMap<String, String> phoneMapMap = new HashMap<>();
                    phoneMapMap.put(username, mobilePhone);
                    project.setPhoneMapMap(phoneMapMap);
                    break;
                }
            }
            if (StringUtil.isEmpty(project)) {
                return projectName + "配置不存在";
            }

            RedmineTask redmineTask = new RedmineTask(json, project.stringToMap(project.getStatusColorMap()), project.getDefaultUrl(),
                    project.getRedmineUrl(), project.getPhoneMapMap());
            String dingMessage = redmine2DingdingMsgHandler(redmineTask, project, template,username);
            memoryData.addWeekReport(redmineTask);
            if ("1".equals(project.getSinglePush())) {

                Class<RedmineTask> redmineTaskClass = RedmineTask.class;
                Field[] declaredFields = redmineTaskClass.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    String fileName = declaredField.getName();
                    String methodName = "get"+fileName.substring(0, 1).toUpperCase() + fileName.substring(1);
                    Method method = redmineTaskClass.getMethod(methodName);
                    //执行method方法，获取返回值
                    Object value = method.invoke(RedmineTask.class);
                }

                //单独推送给个人
                dingMessage = redmineTask.getAssignee()+"\n"+redmineTask.getDescription()+"\n";
//                        MessageFormat.format(template, redmineTask.getSubject(), redmineTask.getProjectName(), redmineTask.getDescription(),
//                        redmineTask.getStatus(), redmineTask.getTaskType(), redmineTask.getPercent(), redmineTask.getRemarks(),
//                        redmineTask.getAuthor(), redmineTask.getPriority(),atPhone , redmineTask.getWatchers(), redmineTask.getEditor(),
//                        redmineTask.getUpdate(), redmineTask.getUrl());




                String s = dingDingService.sendMessageMarkdownByUserName("苑保发,", "测试",
                        dingMessage, project.getCorpId(), project.getCorpSecret(), project.getAgentId());
                return s;
            } else {
                //发送到群里：钉钉机器人
                log.info("dingding msg:{}", dingMessage);
                String weburl = getSecreturl(project.getDingdingWebHookUrl(), project.getCorpSecret());
                String ret = HttpUtil.sendHttpsPost(weburl, dingMessage);

                log.info("dingding ret:{}", ret);
                return ret;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        }
    }

    private String getSecreturl(String dingdingWebHookUrl, String secret) throws Exception {
        // TODO Auto-generated method stub
        Long timestamp = System.currentTimeMillis();
        String sign = "sign";
        System.out.println(sign);

        return dingdingWebHookUrl + "&timestamp=" + timestamp + "&sign=" + sign;
    }

    public void pushWeekReport() throws Exception {
        Map<String, DingMessage> weekReportMap = memoryData.getWeekReport(redmineConfig, true);
        for (Project p : redmineConfig.getProject()) {
            DingMessage dingMessage = weekReportMap.get(p.getName());
            String weburl = getSecreturl(p.getDingdingWebHookUrl(), p.getCorpSecret());
            log.info("dingding msg:{}", dingMessage.getGroupMessage());
            String ret = HttpUtil.sendHttpsPost(weburl, dingMessage.getGroupMessage());
            log.info("dingding ret:{}", ret);
        }
    }

    public String viewWeekReport() {
        return JSON.toJSONString(memoryData.getWeekReport(redmineConfig, false));
    }

    public String redmine2DingdingMsgHandler(RedmineTask redmineTask, Project project, String template,String username) {
        String content = "";
        String phone = project.getPhoneMapMap().get(username);
        String atPhone = "@" + phone + " ";
        content = MessageFormat.format(template, redmineTask.getSubject(), redmineTask.getProjectName(), redmineTask.getDescription(),
                redmineTask.getStatus(), redmineTask.getTaskType(), redmineTask.getPercent(), redmineTask.getRemarks(),
                redmineTask.getAuthor(), redmineTask.getPriority(),atPhone , redmineTask.getWatchers(), redmineTask.getEditor(),
                redmineTask.getUpdate(), redmineTask.getUrl());
        //消息内
        HashMap<String, String> contentMap = new HashMap<>();
        contentMap.put("content", content);
        //通知人
        HashMap<String, Object> atMap = new HashMap<>();
        //1.是否通知所有人
        atMap.put("isAtAll", false);
        List<String> mobileList = new ArrayList<>();
        mobileList.add(phone);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);
        HashMap<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        return JSON.toJSONString(reqMap);
    }
}
